{
 "cells": [
  {
   "cell_type": "raw",
   "id": "2aca8168-62ec-4bba-93f0-73da08cd1920",
   "metadata": {},
   "source": [
    "---\n",
    "title: Summarize Text\n",
    "sidebar_class_name: hidden\n",
    "---"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cf13f702",
   "metadata": {},
   "source": [
    "# Summarize Text\n",
    "\n",
    "```{=mdx}\n",
    ":::info\n",
    "\n",
    "This tutorial demonstrates text summarization using built-in chains and [LangGraph](https://langchain-ai.github.io/langgraphjs/).\n",
    "\n",
    "See [here](https://js.langchain.com/v0.2/docs/tutorials/summarization/) for a previous version of this page, which showcased the legacy chain [RefineDocumentsChain](https://api.js.langchain.com/classes/langchain.chains.RefineDocumentsChain.html).\n",
    "\n",
    ":::\n",
    "```\n",
    "\n",
    "Suppose you have a set of documents (PDFs, Notion pages, customer questions, etc.) and you want to summarize the content. \n",
    "\n",
    "LLMs are a great tool for this given their proficiency in understanding and synthesizing text.\n",
    "\n",
    "In the context of [retrieval-augmented generation](/docs/tutorials/rag), summarizing text can help distill the information in a large number of retrieved documents to provide context for a LLM.\n",
    "\n",
    "In this walkthrough we'll go over how to summarize content from multiple documents using LLMs."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "cc8c5f87-3239-44e1-8772-a97cb6138cc5",
   "metadata": {},
   "source": [
    "## Concepts\n",
    "\n",
    "Concepts we will cover are:\n",
    "\n",
    "- Using [language models](/docs/concepts/chat_models).\n",
    "\n",
    "- Using [document loaders](/docs/concepts/document_loaders), specifically the [CheerioWebBaseLoader](https://api.js.langchain.com/classes/langchain.document_loaders_web_cheerio.CheerioWebBaseLoader.html) to load content from an HTML webpage.\n",
    "\n",
    "- Two ways to summarize or otherwise combine documents.\n",
    "  1. [Stuff](/docs/tutorials/summarization#stuff), which simply concatenates documents into a prompt;\n",
    "  2. [Map-reduce](/docs/tutorials/summarization#map-reduce), for larger sets of documents. This splits documents into batches, summarizes those, and then summarizes the summaries.\n",
    "\n",
    "## Setup\n",
    "\n",
    "### Jupyter Notebook\n",
    "\n",
    "This and other tutorials are perhaps most conveniently run in a [Jupyter notebooks](https://jupyter.org/). Going through guides in an interactive environment is a great way to better understand them. See [here](https://jupyter.org/install) for instructions on how to install.\n",
    "\n",
    "### Installation\n",
    "\n",
    "To install LangChain run:\n",
    "\n",
    "```bash npm2yarn\n",
    "npm i langchain @langchain/core\n",
    "```\n",
    "\n",
    "For more details, see our [Installation guide](/docs/how_to/installation).\n",
    "\n",
    "### LangSmith\n",
    "\n",
    "Many of the applications you build with LangChain will contain multiple steps with multiple invocations of LLM calls.\n",
    "As these applications get more and more complex, it becomes crucial to be able to inspect what exactly is going on inside your chain or agent.\n",
    "The best way to do this is with [LangSmith](https://smith.langchain.com).\n",
    "\n",
    "After you sign up at the link above, make sure to set your environment variables to start logging traces:\n",
    "\n",
    "```shell\n",
    "export LANGSMITH_TRACING=\"true\"\n",
    "export LANGSMITH_API_KEY=\"...\"\n",
    "\n",
    "# Reduce tracing latency if you are not in a serverless environment\n",
    "# export LANGCHAIN_CALLBACKS_BACKGROUND=true\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4715b4ff",
   "metadata": {},
   "source": [
    "## Overview\n",
    "\n",
    "A central question for building a summarizer is how to pass your documents into the LLM's context window. Two common approaches for this are:\n",
    "\n",
    "1. `Stuff`: Simply \"stuff\" all your documents into a single prompt. This is the simplest approach.\n",
    "\n",
    "2. `Map-reduce`: Summarize each document on its own in a \"map\" step and then \"reduce\" the summaries into a final summary.\n",
    "\n",
    "Note that map-reduce is especially effective when understanding of a sub-document does not rely on preceding context. For example, when summarizing a corpus of many, shorter documents. In other cases, such as summarizing a novel or body of text with an inherent sequence, [iterative refinement](https://js.langchain.com/v0.2/docs/tutorials/summarization/) may be more effective."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "21541329-f883-42ca-bc94-ab9793951dfa",
   "metadata": {},
   "source": [
    "First we load in our documents. We will use [WebBaseLoader](https://python.langchain.com/api_reference/community/document_loaders/langchain_community.document_loaders.web_base.WebBaseLoader.html) to load a blog post:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "5f5c7c49-782d-4835-82f3-ef114e0d6d68",
   "metadata": {},
   "outputs": [],
   "source": [
    "import \"cheerio\";\n",
    "import { CheerioWebBaseLoader } from \"@langchain/community/document_loaders/web/cheerio\";\n",
    "\n",
    "const pTagSelector = \"p\";\n",
    "const cheerioLoader = new CheerioWebBaseLoader(\n",
    "  \"https://lilianweng.github.io/posts/2023-06-23-agent/\",\n",
    "  {\n",
    "    selector: pTagSelector\n",
    "  }\n",
    ");\n",
    "\n",
    "const docs = await cheerioLoader.load();"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "22548ae0-7f67-4dd0-a3f8-d6675b38df53",
   "metadata": {},
   "source": [
    "Let's next select a [chat model](/docs/integrations/chat/):\n",
    "\n",
    "```{=mdx}\n",
    "import ChatModelTabs from \"@theme/ChatModelTabs\";\n",
    "\n",
    "<ChatModelTabs customVarName=\"llm\" />\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "b1c639d9-b27c-4e71-9312-d2666b05f1e3",
   "metadata": {},
   "outputs": [],
   "source": [
    "// @lc-docs-hide-cell\n",
    "import { ChatOpenAI } from '@langchain/openai';\n",
    "\n",
    "const llm = new ChatOpenAI({\n",
    "  model: \"gpt-4o-mini\",\n",
    "  temperature: 0,\n",
    "})"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "615b36e1",
   "metadata": {},
   "source": [
    "## Stuff: summarize in a single LLM call {#stuff}\n",
    "\n",
    "We can use [createStuffDocumentsChain](https://api.js.langchain.com/functions/langchain.chains_combine_documents.createStuffDocumentsChain.html), especially if using larger context window models such as:\n",
    "\n",
    "* 128k token OpenAI `gpt-4o` \n",
    "* 200k token Anthropic `claude-3-5-sonnet-20240620`\n",
    "\n",
    "The chain will take a list of documents, insert them all into a prompt, and pass that prompt to an LLM:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "3557a505-3688-479b-8075-14e948b43d40",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "The retrieved documents discuss the development and capabilities of autonomous agents powered by large language models (LLMs). Here are the main themes:\n",
      "\n",
      "1. **LLM as a Core Controller**: LLMs are positioned as the central intelligence in autonomous agent systems, capable of performing complex tasks beyond simple text generation. They can be framed as general problem solvers, with various implementations like AutoGPT, GPT-Engineer, and BabyAGI serving as proof-of-concept demonstrations.\n",
      "\n",
      "2. **Task Decomposition and Planning**: Effective task management is crucial for LLMs. Techniques like Chain of Thought (CoT) and Tree of Thoughts (ToT) are highlighted for breaking down complex tasks into manageable steps. CoT encourages step-by-step reasoning, while ToT explores multiple reasoning paths, enhancing the agent's problem-solving capabilities.\n",
      "\n",
      "3. **Integration of External Tools**: The use of external tools significantly enhances LLM capabilities. Frameworks like MRKL and Toolformer allow LLMs to interact with various APIs and tools, improving their performance in specific tasks. This modular approach enables LLMs to route inquiries to specialized modules, combining neural and symbolic reasoning.\n",
      "\n",
      "4. **Self-Reflection and Learning**: Self-reflection mechanisms are essential for agents to learn from past actions and improve over time. Approaches like ReAct and Reflexion integrate reasoning with action, allowing agents to evaluate their performance and adjust strategies based on feedback.\n",
      "\n",
      "5. **Memory and Context Management**: The documents discuss different types of memory (sensory, short-term, long-term) and their relevance to LLMs. The challenge of finite context length in LLMs is emphasized, as it limits the ability to retain and utilize historical information effectively. Techniques like external memory storage and vector databases are suggested to mitigate these limitations.\n",
      "\n",
      "6. **Challenges and Limitations**: Several challenges are identified, including the reliability of natural language interfaces, difficulties in long-term planning, and the need for robust task decomposition. The documents note that LLMs may struggle with unexpected errors and formatting issues, which can hinder their performance in real-world applications.\n",
      "\n",
      "7. **Emerging Applications**: The potential applications of LLM-powered agents are explored, including scientific discovery, autonomous design, and interactive simulations (e.g., generative agents mimicking human behavior). These applications demonstrate the versatility and innovative possibilities of LLMs in various domains.\n",
      "\n",
      "Overall, the documents present a comprehensive overview of the current state of LLM-powered autonomous agents, highlighting their capabilities, methodologies, and the challenges they face in practical implementations.\n"
     ]
    }
   ],
   "source": [
    "import { createStuffDocumentsChain } from \"langchain/chains/combine_documents\";\n",
    "import { StringOutputParser } from \"@langchain/core/output_parsers\";\n",
    "import { PromptTemplate } from \"@langchain/core/prompts\";\n",
    "\n",
    "\n",
    "// Define prompt\n",
    "const prompt = PromptTemplate.fromTemplate(\n",
    "  \"Summarize the main themes in these retrieved docs: {context}\"\n",
    ");\n",
    "\n",
    "// Instantiate\n",
    "const chain = await createStuffDocumentsChain({\n",
    "  llm: llm,\n",
    "  outputParser: new StringOutputParser(),\n",
    "  prompt,\n",
    "});\n",
    "\n",
    "// Invoke\n",
    "const result = await chain.invoke({context: docs})\n",
    "console.log(result)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "02d5a634-203c-4e43-ac55-4e502be095d3",
   "metadata": {},
   "source": [
    "### Streaming\n",
    "\n",
    "Note that we can also stream the result token-by-token:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "c62ca04a-aea0-49ec-8074-1b88dec1f872",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "|The| retrieved| documents| discuss| the| development| and| capabilities| of| autonomous| agents| powered| by| large| language| models| (|LL|Ms|).| Here| are| the| main| themes|:\n",
      "\n",
      "|1|.| **|LL|M| as| a| Core| Controller|**|:| L|LM|s| are| positioned| as| the| central| intelligence| in| autonomous| agent| systems|,| capable| of| performing| complex| tasks| beyond| simple| text| generation|.| They| can| be| framed| as| general| problem| sol|vers|,| with| various| implementations| like| Auto|GPT|,| GPT|-|Engineer|,| and| Baby|AG|I| serving| as| proof|-of|-con|cept| demonstrations|.\n",
      "\n",
      "|2|.| **|Task| De|composition| and| Planning|**|:| Effective| task| management| is| crucial| for| L|LM|s| to| handle| complicated| tasks|.| Techniques| like| Chain| of| Thought| (|Co|T|)| and| Tree| of| Thoughts| (|To|T|)| are| highlighted| for| breaking| down| tasks| into| manageable| steps| and| exploring| multiple| reasoning| paths|.| Additionally|,| L|LM|+|P| integrates| classical| planning| methods| to| enhance| long|-term| planning| capabilities|.\n",
      "\n",
      "|3|.| **|Self|-|Reflection| and| Learning|**|:| Self|-ref|lection| mechanisms| are| essential| for| agents| to| learn| from| past| actions| and| improve| their| decision|-making| processes|.| Framework|s| like| Re|Act| and| Reflex|ion| incorporate| dynamic| memory| and| self|-ref|lection| to| refine| reasoning| skills| and| enhance| performance| through| iterative| learning|.\n",
      "\n",
      "|4|.| **|Tool| Util|ization|**|:| The| integration| of| external| tools| significantly| extends| the| capabilities| of| L|LM|s|.| Appro|aches| like| MR|KL| and| Tool|former| demonstrate| how| L|LM|s| can| be| augmented| with| various| APIs| to| perform| specialized| tasks|,| enhancing| their| functionality| in| real|-world| applications|.\n",
      "\n",
      "|5|.| **|Memory| and| Context| Management|**|:| The| documents| discuss| different| types| of| memory| (|sens|ory|,| short|-term|,| long|-term|)| and| their| relevance| to| L|LM|s|.| The| challenge| of| finite| context| length| is| emphasized|,| as| it| limits| the| model|'s| ability| to| retain| and| utilize| historical| information| effectively|.| Techniques| like| vector| stores| and| approximate| nearest| neighbors| (|ANN|)| are| suggested| to| improve| retrieval| speed| and| memory| management|.\n",
      "\n",
      "|6|.| **|Challenges| and| Limit|ations|**|:| Several| limitations| of| current| L|LM|-powered| agents| are| identified|,| including| issues| with| the| reliability| of| natural| language| interfaces|,| difficulties| in| long|-term| planning|,| and| the| need| for| improved| efficiency| in| task| execution|.| The| documents| also| highlight| the| importance| of| human| feedback| in| refining| model| outputs| and| addressing| potential| biases|.\n",
      "\n",
      "|7|.| **|Emer|ging| Applications|**|:| The| potential| applications| of| L|LM|-powered| agents| are| explored|,| including| scientific| discovery|,| autonomous| design|,| and| interactive| simulations| (|e|.g|.,| gener|ative| agents|).| These| applications| showcase| the| versatility| of| L|LM|s| in| various| domains|,| from| drug| discovery| to| social| behavior| simulations|.\n",
      "\n",
      "|Overall|,| the| documents| present| a| comprehensive| overview| of| the| current| state| of| L|LM|-powered| autonomous| agents|,| their| capabilities|,| methodologies| for| improvement|,| and| the| challenges| they| face| in| practical| applications|.|||"
     ]
    }
   ],
   "source": [
    "const stream = await chain.stream({context: docs});\n",
    "\n",
    "for await (const token of stream) {\n",
    "  process.stdout.write(token + \"|\");\n",
    "}"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4e4e4a43",
   "metadata": {},
   "source": [
    "### Go deeper\n",
    "\n",
    "* You can easily customize the prompt. \n",
    "* You can easily try different LLMs, (e.g., [Claude](/docs/integrations/chat/anthropic)) via the `llm` parameter."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ad6cabee",
   "metadata": {},
   "source": [
    "## Map-Reduce: summarize long texts via parallelization {#map-reduce}\n",
    "\n",
    "Let's unpack the map reduce approach. For this, we'll first map each document to an individual summary using an LLM. Then we'll reduce or consolidate those summaries into a single global summary.\n",
    "\n",
    "Note that the map step is typically parallelized over the input documents.\n",
    "\n",
    "[LangGraph](https://langchain-ai.github.io/langgraphjs/), built on top of [@langchain/core](/docs/concepts/architecture#langchaincore), supports [map-reduce](https://langchain-ai.github.io/langgraphjs/how-tos/map-reduce/) workflows and is well-suited to this problem:\n",
    "\n",
    "- LangGraph allows for individual steps (such as successive summarizations) to be streamed, allowing for greater control of execution;\n",
    "- LangGraph's [checkpointing](https://langchain-ai.github.io/langgraphjs/how-tos/persistence/) supports error recovery, extending with human-in-the-loop workflows, and easier incorporation into conversational applications.\n",
    "- The LangGraph implementation is straightforward to modify and extend, as we will see below.\n",
    "\n",
    "### Map\n",
    "Let's first define the prompt associated with the map step. We can use the same summarization prompt as in the `stuff` approach, above:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "f32e43e2-0dd4-4e1c-8b2c-7e05b7e61570",
   "metadata": {},
   "outputs": [],
   "source": [
    "import { ChatPromptTemplate } from \"@langchain/core/prompts\";\n",
    "\n",
    "const mapPrompt = ChatPromptTemplate.fromMessages(\n",
    "  [\n",
    "    [\"user\", \"Write a concise summary of the following: \\n\\n{context}\"]\n",
    "  ]\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "272ce8ce-919d-4ded-bbd5-a53a8a30bc66",
   "metadata": {},
   "source": [
    "We can also use the Prompt Hub to store and fetch prompts.\n",
    "\n",
    "This will work with your [LangSmith API key](https://docs.smith.langchain.com/).\n",
    "\n",
    "For example, see the map prompt [here](https://smith.langchain.com/hub/rlm/map-prompt).\n",
    "\n",
    "```javascript\n",
    "import { pull } from \"langchain/hub\";\n",
    "import { ChatPromptTemplate } from \"@langchain/core/prompts\";\n",
    "\n",
    "const mapPrompt = await pull<ChatPromptTemplate>(\"rlm/map-prompt\");\n",
    "```"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "bee3c331",
   "metadata": {},
   "source": [
    "### Reduce\n",
    "\n",
    "We also define a prompt that takes the document mapping results and reduces them into a single output."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "802f95cd-81b6-445e-8d03-820bf4625e25",
   "metadata": {},
   "outputs": [],
   "source": [
    "// Also available via the hub at `rlm/reduce-prompt`\n",
    "let reduceTemplate = `\n",
    "The following is a set of summaries:\n",
    "{docs}\n",
    "Take these and distill it into a final, consolidated summary\n",
    "of the main themes.\n",
    "`\n",
    "\n",
    "const reducePrompt = ChatPromptTemplate.fromMessages(\n",
    "  [\n",
    "    [\"user\", reduceTemplate]\n",
    "  ]\n",
    ")"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3d7df564-415a-49e2-80b6-743446b40be5",
   "metadata": {},
   "source": [
    "### Orchestration via LangGraph\n",
    "\n",
    "Below we implement a simple application that maps the summarization step on a list of documents, then reduces them using the above prompts.\n",
    "\n",
    "Map-reduce flows are particularly useful when texts are long compared to the context window of a LLM. For long texts, we need a mechanism that ensures that the context to be summarized in the reduce step does not exceed a model's context window size. Here we implement a recursive \"collapsing\" of the summaries: the inputs are partitioned based on a token limit, and summaries are generated of the partitions. This step is repeated until the total length of the summaries is within a desired limit, allowing for the summarization of arbitrary-length text.\n",
    "\n",
    "First we chunk the blog post into smaller \"sub documents\" to be mapped:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "68491eef-d898-4a9a-b4a8-3f49b6237e6a",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Generated 6 documents.\n"
     ]
    }
   ],
   "source": [
    "import { TokenTextSplitter } from \"@langchain/textsplitters\";\n",
    "\n",
    "const textSplitter = new TokenTextSplitter({\n",
    "  chunkSize: 1000,\n",
    "  chunkOverlap: 0,\n",
    "});\n",
    "\n",
    "const splitDocs = await textSplitter.splitDocuments(docs)\n",
    "console.log(`Generated ${splitDocs.length} documents.`)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3e7f1c8a-070e-47f0-bcf2-16d6191051ac",
   "metadata": {},
   "source": [
    "Next, we define our graph. Note that we define an artificially low maximum token length of 1,000 tokens to illustrate the \"collapsing\" step."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "a8d60848-7c83-4bc1-882a-2184df91fc07",
   "metadata": {},
   "outputs": [],
   "source": [
    "import {\n",
    "  collapseDocs,\n",
    "  splitListOfDocs,\n",
    "} from \"langchain/chains/combine_documents/reduce\";\n",
    "import { Document } from \"@langchain/core/documents\";\n",
    "import { StateGraph, Annotation, Send } from \"@langchain/langgraph\";\n",
    "\n",
    "\n",
    "let tokenMax = 1000\n",
    "\n",
    "\n",
    "async function lengthFunction(documents) {\n",
    "    const tokenCounts = await Promise.all(documents.map(async (doc) => {\n",
    "        return llm.getNumTokens(doc.pageContent);\n",
    "    }));\n",
    "    return tokenCounts.reduce((sum, count) => sum + count, 0);\n",
    "}\n",
    "\n",
    "const OverallState = Annotation.Root({\n",
    "  contents: Annotation<string[]>,\n",
    "  // Notice here we pass a reducer function.\n",
    "  // This is because we want combine all the summaries we generate\n",
    "  // from individual nodes back into one list. - this is essentially\n",
    "  // the \"reduce\" part\n",
    "  summaries: Annotation<string[]>({\n",
    "    reducer: (state, update) => state.concat(update),\n",
    "  }),\n",
    "  collapsedSummaries: Annotation<Document[]>,\n",
    "  finalSummary: Annotation<string>,\n",
    "});\n",
    "\n",
    "\n",
    "// This will be the state of the node that we will \"map\" all\n",
    "// documents to in order to generate summaries\n",
    "interface SummaryState {\n",
    "  content: string;\n",
    "}\n",
    "\n",
    "// Here we generate a summary, given a document\n",
    "const generateSummary = async (state: SummaryState): Promise<{ summaries: string[] }> => {\n",
    "  const prompt = await mapPrompt.invoke({context: state.content});\n",
    "  const response = await llm.invoke(prompt);\n",
    "  return { summaries: [String(response.content)] };\n",
    "};\n",
    "\n",
    "\n",
    "// Here we define the logic to map out over the documents\n",
    "// We will use this an edge in the graph\n",
    "const mapSummaries = (state: typeof OverallState.State) => {\n",
    "  // We will return a list of `Send` objects\n",
    "  // Each `Send` object consists of the name of a node in the graph\n",
    "  // as well as the state to send to that node\n",
    "  return state.contents.map((content) => new Send(\"generateSummary\", { content }));\n",
    "};\n",
    "\n",
    "\n",
    "const collectSummaries = async (state: typeof OverallState.State) => {\n",
    "  return {\n",
    "      collapsedSummaries: state.summaries.map(summary => new Document({pageContent: summary}))\n",
    "  };\n",
    "}\n",
    "\n",
    "\n",
    "async function _reduce(input) {\n",
    "    const prompt = await reducePrompt.invoke({ docs: input });\n",
    "    const response = await llm.invoke(prompt);\n",
    "    return String(response.content);\n",
    "}\n",
    "\n",
    "// Add node to collapse summaries\n",
    "const collapseSummaries = async (state: typeof OverallState.State) => {\n",
    "  const docLists = splitListOfDocs(state.collapsedSummaries, lengthFunction, tokenMax);\n",
    "  const results = [];\n",
    "  for (const docList of docLists) {\n",
    "      results.push(await collapseDocs(docList, _reduce));\n",
    "  }\n",
    "\n",
    "  return { collapsedSummaries: results };\n",
    "}\n",
    "\n",
    "\n",
    "// This represents a conditional edge in the graph that determines\n",
    "// if we should collapse the summaries or not\n",
    "async function shouldCollapse(state: typeof OverallState.State) {\n",
    "  let numTokens = await lengthFunction(state.collapsedSummaries);\n",
    "  if (numTokens > tokenMax) {\n",
    "    return \"collapseSummaries\";\n",
    "  } else {\n",
    "    return \"generateFinalSummary\";\n",
    "  }\n",
    "}\n",
    "\n",
    "\n",
    "// Here we will generate the final summary\n",
    "const generateFinalSummary = async (state: typeof OverallState.State) => {\n",
    "  const response = await _reduce(state.collapsedSummaries);\n",
    "  return { finalSummary: response}\n",
    "}\n",
    "\n",
    "// Construct the graph\n",
    "const graph = new StateGraph(OverallState)\n",
    "  .addNode(\"generateSummary\", generateSummary)\n",
    "  .addNode(\"collectSummaries\", collectSummaries)\n",
    "  .addNode(\"collapseSummaries\", collapseSummaries)\n",
    "  .addNode(\"generateFinalSummary\", generateFinalSummary)\n",
    "  .addConditionalEdges(\n",
    "    \"__start__\",\n",
    "    mapSummaries,\n",
    "    [\"generateSummary\"]\n",
    "  )\n",
    "  .addEdge(\"generateSummary\", \"collectSummaries\")\n",
    "  .addConditionalEdges(\n",
    "    \"collectSummaries\",\n",
    "    shouldCollapse,\n",
    "    [\"collapseSummaries\", \"generateFinalSummary\"]\n",
    "  )\n",
    "  .addConditionalEdges(\n",
    "    \"collapseSummaries\",\n",
    "    shouldCollapse,\n",
    "    [\"collapseSummaries\", \"generateFinalSummary\"]\n",
    "  )\n",
    "  .addEdge(\"generateFinalSummary\", \"__end__\")\n",
    "\n",
    "const app = graph.compile();"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "3b04dcc5-6487-45f0-96ff-0f8a56276b92",
   "metadata": {},
   "source": [
    "LangGraph allows the graph structure to be plotted to help visualize its function:"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c1440b23-625a-466d-8380-7cfe7459e063",
   "metadata": {},
   "source": [
    "```javascript\n",
    "// Note: tslab only works inside a jupyter notebook. Don't worry about running this code yourself!\n",
    "import * as tslab from \"tslab\";\n",
    "\n",
    "const image = await app.getGraph().drawMermaidPng();\n",
    "const arrayBuffer = await image.arrayBuffer();\n",
    "\n",
    "await tslab.display.png(new Uint8Array(arrayBuffer));\n",
    "```\n",
    "\n",
    "![graph_img_summarization](../../static/img/graph_img_summarization.png)"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "346c025c-67ef-4939-8742-9bcbf9a06f66",
   "metadata": {},
   "source": [
    "When running the application, we can stream the graph to observe its sequence of steps. Below, we will simply print out the name of the step.\n",
    "\n",
    "Note that because we have a loop in the graph, it can be helpful to specify a [recursion_limit](https://langchain-ai.github.io/langgraphjs/reference/classes/langgraph.GraphRecursionError.html) on its execution. This will raise a specific error when the specified limit is exceeded."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "id": "68efeaaa-d013-4605-a2a0-e089e6b2b6d0",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[ \u001b[32m'generateSummary'\u001b[39m ]\n",
      "[ \u001b[32m'generateSummary'\u001b[39m ]\n",
      "[ \u001b[32m'generateSummary'\u001b[39m ]\n",
      "[ \u001b[32m'generateSummary'\u001b[39m ]\n",
      "[ \u001b[32m'generateSummary'\u001b[39m ]\n",
      "[ \u001b[32m'generateSummary'\u001b[39m ]\n",
      "[ \u001b[32m'collectSummaries'\u001b[39m ]\n",
      "[ \u001b[32m'generateFinalSummary'\u001b[39m ]\n"
     ]
    }
   ],
   "source": [
    "let finalSummary = null;\n",
    "\n",
    "for await (\n",
    "  const step of await app.stream(\n",
    "    {contents: splitDocs.map(doc => doc.pageContent)},\n",
    "    { recursionLimit: 10 }\n",
    "  )\n",
    ") {\n",
    "  console.log(Object.keys(step));\n",
    "  if (step.hasOwnProperty(\"generateFinalSummary\")) {\n",
    "      finalSummary = step.generateFinalSummary\n",
    "  }\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "id": "b606986d-ce3e-454d-8dad-3ca7d9e67c39",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\n",
      "  finalSummary: \u001b[32m'The summaries highlight the evolving landscape of large language models (LLMs) and their integration into autonomous agents and various applications. Key themes include:\\n'\u001b[39m +\n",
      "    \u001b[32m'\\n'\u001b[39m +\n",
      "    \u001b[32m'1. **Autonomous Agents and LLMs**: Projects like AutoGPT and GPT-Engineer demonstrate the potential of LLMs as core controllers in autonomous systems, utilizing techniques such as Chain of Thought (CoT) and Tree of Thoughts (ToT) for task management and reasoning. These agents can learn from past actions through self-reflection mechanisms, enhancing their problem-solving capabilities.\\n'\u001b[39m +\n",
      "    \u001b[32m'\\n'\u001b[39m +\n",
      "    \u001b[32m'2. **Supervised Fine-Tuning and Human Feedback**: The importance of human feedback in fine-tuning models is emphasized, with methods like Algorithm Distillation (AD) showing promise in improving model performance while preventing overfitting. The integration of various memory types and external memory systems is suggested to enhance cognitive capabilities.\\n'\u001b[39m +\n",
      "    \u001b[32m'\\n'\u001b[39m +\n",
      "    \u001b[32m'3. **Integration of External Tools**: The incorporation of external tools and APIs significantly extends LLM capabilities, particularly in specialized tasks like maximum inner-product search (MIPS) and domain-specific applications such as ChemCrow for drug discovery. Frameworks like MRKL and HuggingGPT illustrate the potential for LLMs to effectively utilize these tools.\\n'\u001b[39m +\n",
      "    \u001b[32m'\\n'\u001b[39m +\n",
      "    \u001b[32m'4. **Evaluation Discrepancies**: There are notable discrepancies between LLM-based assessments and expert evaluations, indicating that LLMs may struggle with specialized knowledge. This raises concerns about their reliability in critical applications, such as scientific discovery.\\n'\u001b[39m +\n",
      "    \u001b[32m'\\n'\u001b[39m +\n",
      "    \u001b[32m'5. **Limitations of LLMs**: Despite advancements, LLMs face limitations, including finite context lengths, challenges in long-term planning, and difficulties in adapting to unexpected errors. These constraints hinder their robustness compared to human capabilities.\\n'\u001b[39m +\n",
      "    \u001b[32m'\\n'\u001b[39m +\n",
      "    \u001b[32m'Overall, the advancements in LLMs and their applications reveal both their potential and limitations, emphasizing the need for ongoing research and development to enhance their effectiveness in various domains.'\u001b[39m\n",
      "}\n"
     ]
    }
   ],
   "source": [
    "finalSummary"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a9e33d11-7a2a-4693-8c87-88b88eebc896",
   "metadata": {},
   "source": [
    "In the corresponding [LangSmith trace](https://smith.langchain.com/public/467d535b-1732-46ee-8d3b-f44d9cea7efa/r) we can see the individual LLM calls, grouped under their respective nodes.\n",
    "\n",
    "### Go deeper\n",
    " \n",
    "**Customization** \n",
    "\n",
    "* As shown above, you can customize the LLMs and prompts for map and reduce stages.\n",
    "\n",
    "**Real-world use-case**\n",
    "\n",
    "* See [this blog post](https://blog.langchain.dev/llms-to-improve-documentation/) case-study on analyzing user interactions (questions about LangChain documentation)!  \n",
    "* The blog post and associated [repo](https://github.com/mendableai/QA_clustering) also introduce clustering as a means of summarization.\n",
    "* This opens up another path beyond the `stuff` or `map-reduce` approaches that is worth considering."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "e8680f94-c872-4d36-92e5-1462ffeb577d",
   "metadata": {},
   "source": [
    "## Next steps\n",
    "\n",
    "We encourage you to check out the [how-to guides](/docs/how_to) for more detail on: \n",
    "\n",
    "- Built-in [document loaders](/docs/how_to/#document-loaders) and [text-splitters](/docs/how_to/#text-splitters)\n",
    "- Integrating various combine-document chains into a [RAG application](/docs/tutorials/rag/)\n",
    "- Incorporating retrieval into a [chatbot](/docs/how_to/chatbots_retrieval/)\n",
    "\n",
    "and other concepts."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "TypeScript",
   "language": "typescript",
   "name": "tslab"
  },
  "language_info": {
   "codemirror_mode": {
    "mode": "typescript",
    "name": "javascript",
    "typescript": true
   },
   "file_extension": ".ts",
   "mimetype": "text/typescript",
   "name": "typescript",
   "version": "3.7.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
